package seedpod.model;

/**
 * A container between an object instance and an attribute that has multiple values.
 */
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import seedpod.exceptions.SeedpodException;
import seedpod.kb2db.ClsMap;
import seedpod.kb2db.SlotMap;
import seedpod.model.rdb.RdbValueType;
import seedpod.rdb.PMFactory;
import seedpod.rdb.PManager;
import seedpod.rdb.RdbConnection;
import seedpod.rdb.SqlUtil;

public class ValueSetRelationship extends Relationship {

	/**
	 * Object-Value pair. Object is represented by its OID. Value can be of type Object.
	 * 
	 * @author Maya Hao Li
	 * 
	 */
	class OVPair extends GenericPair {

		OVPair(Integer oid, Object value) {
			super( oid, value );
		}

		@Override
		public Integer getSource() {
			return (Integer)super.getSource();
		}

		@Override
		public Object getTarget() {
			return super.getTarget();
		}
	}

	protected SlotMap relationshipSlot;
	protected ArrayList<OVPair> targetValueSet = new ArrayList<OVPair>();

	public ValueSetRelationship(SlotMap slot) {
		super( slot );
	}

	public ValueSetRelationship(SlotMap slot, int srcOid) throws SeedpodException {
		super( slot, srcOid );
	}

	public ValueSetRelationship(SlotMap slot, SeedpodDO sourceObj) {
		super( slot, sourceObj );
	}

	public void addTarget( Object target ) {
		targetValueSet.add( new OVPair( getSourceOid(), target ) );
	}

	@Override
	public ArrayList<Object> getTargetObjects() {
		ArrayList<Object> objSet = new ArrayList<Object>();
		for ( OVPair ovpair : targetValueSet )
			objSet.add( ovpair.getTarget() );
		return objSet;
	}

	/**
	 * Query for the set of simple type values in the reified table.
	 */
	public void initalize() {
		PManager manager;
		String sql = null;
		String reifiedClsName = getTargetClassName( _relationSlot );
		RdbValueType dbType = _relationSlot.getRdbValueType();
		ClsMap reifiedCls = null;

		// Must be relation
		if ( !dbType.equals( RdbValueType.RELATION ) ) return;

		// get PManager
		try {
			manager = PMFactory.getInstance().createManager();
		} catch (SeedpodException e1) {
			return;
		}

		// create SQL query, SELECT [TO.SLOT] FROM [REIFIED.CLASS] WHERE [FROM.OID]=SOURCE_OID.
		reifiedCls = manager.getModelMap().getClsMap( reifiedClsName );
		if ( reifiedCls == null ) return;
		SlotMap from = getFromSlot( reifiedCls );
		SlotMap to = getToSlot( reifiedCls );
		sql = "SELECT " + SqlUtil.QQ( to.getName() ) + " FROM " + SqlUtil.QQ( reifiedClsName ) + " WHERE  " + SqlUtil.QQ( from.getName() ) + " = " + _sourceOid;

		// submit the query and retrieve IDs
		if ( sql != null ) try {
			RdbConnection conn = manager.getRdbConnection();
			ResultSet rs = conn.executeQuery( sql );
			while (rs.next()) {
				Object target = rs.getObject( 1 );
				addTarget( target );
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}

	public void save() {
		// TODO Auto-generated method stub
		
	}

}